import { Handler, HTTPRequest, HTTPResponse } from "puppeteer";
import * as fs from 'fs';
import * as path from 'path';

const ignoreExts = ['.css', '.js', '.jpg', '.jpeg', '.avif', '.png', '.gif', '.bmp', '.webp', '.svg', '.ico', '.woff', '.woff2', '.ttf', '.eot', '.otf', '.webp', '.svg', '.ico', '.woff', '.woff2', '.ttf', '.eot', '.otf'];
const ignorePrefixes = ['data:'];
const ignoreUrls = ['/log/web', '/v2/log/web'];

const URL_MSG_AT = 'https://api.bilibili.com/x/msgfeed/at';

function isIgnoreExt(url: string): boolean {
    // 移除查询参数和锚点，只检查路径部分
    const pathname = url.split('?')[0].split('#')[0];
    return ignoreExts.some(ext => pathname.endsWith(ext));
}

function isIgnorePrefix(url: string): boolean {
    return ignorePrefixes.some(prefix => url.startsWith(prefix));
}

function isIgnoreUrl(url: string): boolean {
    return ignoreUrls.some(ignoreUrl => url.includes(ignoreUrl));
}


export function onRequest(tempPath: string): Handler<HTTPRequest> {
    tempPath = path.join(tempPath, 'request');
    if (!fs.existsSync(tempPath)) {
        fs.mkdirSync(tempPath, { recursive: true });
    }
    return async (request: HTTPRequest) => {
        const url = request.url();
        const method = request.method();
        const headers = request.headers();
        const postData = request.postData();
        if (isIgnoreExt(url) || isIgnorePrefix(url) || isIgnoreUrl(url) || method === 'OPTIONS') {
            return;
        }
        
        const timestamp = Date.now();
        const fileName = `${timestamp}.txt`;
        fs.openSync(path.join(tempPath, fileName), 'w');
        fs.appendFileSync(path.join(tempPath, fileName), `${url}\n${method}\n${postData}\n`);
        console.log(`[REQUEST] ${method} ${url}`);
        if (url.includes('api.bilibili.com')) {
            console.log(`[API REQUEST] ${method} ${url}`);
        }
    }
}
export function onResponse(tempPath: string): Handler<HTTPResponse> {
    tempPath = path.join(tempPath, 'response');
    if (!fs.existsSync(tempPath)) {
        fs.mkdirSync(tempPath, { recursive: true });
    }
    return async (response: HTTPResponse) => {
        const timestamp = Date.now();
        const fileName = `${timestamp}.txt`;
        try {
            // 检查请求的URL是否是你关心的
            const url = response.url();
            const method = response.request().method();
            if (isIgnoreExt(url) || isIgnorePrefix(url) || isIgnoreUrl(url) || method === 'OPTIONS') {
                return;
            }
            const status = response.status();
            const headers = response.headers();
            const headersString = Object.entries(headers).map(([key, value]) => `${key}: ${value}`).join('\n');
            const text = await response.text();
            // 创建文件
            fs.openSync(path.join(tempPath, fileName), 'w');
            // 写入文件
            fs.appendFileSync(path.join(tempPath, fileName), `${url}\n${status}\n${headersString}\n${text}\n`);
        } catch (error) {
            console.error(error);
            fs.openSync(path.join(tempPath, fileName), 'w');
            fs.appendFileSync(path.join(tempPath, fileName), `${error}\n`);
        }
    }
}